use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

use anyhow::Ok;
use model_graph_types::{
    container::workflow::{
        WorkflowBlock, WorkflowBlockBody, WorkflowBlockBuilder, WorkflowBlockExecuteResult,
        WorkflowBlockExecuteResultBuilder, WorkflowBlockExecuteResultStatus, WorkflowBlockStart,
        WorkflowBlockStartBuilder, WorkflowGraphNodeData, WorkflowGraphNodeStart,
    },
    modeling::Value,
};

use crate::workflow::context::{Getter, WorkflowContext};

pub fn is_start(node: &WorkflowGraphNodeData) -> bool {
    match node {
        WorkflowGraphNodeData::Start(_) => true,
        _ => false,
    }
}

pub async fn compile(id: &String, node: &WorkflowGraphNodeStart) -> anyhow::Result<WorkflowBlock> {
    return Ok(WorkflowBlockBuilder::default()
        .id(id)
        .body(WorkflowBlockBody::Start(
            WorkflowBlockStartBuilder::default()
                .variables(node.variables.clone())
                .build()?,
        ))
        .build()?);
}

pub fn execute(
    block: &WorkflowBlockStart,
    context: Arc<Mutex<WorkflowContext>>,
) -> anyhow::Result<WorkflowBlockExecuteResult> {
    //
    let mut outputs: HashMap<String, Value> = HashMap::new();

    for item in &block.variables {
        //从context中获取值
        let value = context.get(&item.variable)?;
        outputs.insert(item.variable.clone(), value);
    }

    Ok(WorkflowBlockExecuteResultBuilder::default()
        .status(WorkflowBlockExecuteResultStatus::Succeeded)
        .result(outputs)
        .source_handle("source")
        .build()?)
}
